<script setup lang="ts">
import { useDefineDelayRender } from './defineDelayRender'
import type {
  DelayRenderGroupProps,
  RegisterParams,
} from './type'
import {
  groupRegisterIdentity,
  groupStatusIdentity,
} from './'

defineOptions({
  inheritAttrs: false,
})
const props = withDefaults(
  defineProps<DelayRenderGroupProps>(),
  {
    step: 1,
  },
)
// ------------------use------------------
//#
const [isRender, setIsRender] = useState(false)
const { updataFrameIndex, registerFrameCallback }
  = useDefineDelayRender(-1)
const renderSet = new Set<RegisterParams>()
registerFrameCallback((n: number) => {
  if (props.maxFrame && props.maxFrame < n)
    return true
  if (renderSet.size === 0)
    return true
  for (const p of renderSet.values()) {
    if (n < p.frame)
      continue
    p.setStatus(true)
    renderSet.delete(p)
  }
  return false
})
init()
// #endregion
// ------------------静态变量------------------
// #region
// !用于给子项累加添加帧
let frameIndex = 1
// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region

// #endregion
// ------------------reactive------
// #region

// #endregion
// ------------------computed------
// #region

// #endregion
// ------------------生命周期------------------
// #region

// #endregion
// ------------------内置方法---------------------
// #region

// #endregion
// ------------------方法---------------------
// #region
function init() {
  if (props.delay) {
    sleep(props.delay).then(() => {
      setIsRender(true)
      updataFrameIndex()
    })
  }
  else {
    setIsRender(true)
    updataFrameIndex()
  }
}
function register(params: RegisterParams) {
  if (params.frame === 1) {
    params.frame = frameIndex
    frameIndex += props.step
  }
  renderSet.add(params)
}
// #endregion
// !告知处于渲染组内
provide(groupStatusIdentity, true)
provide(groupRegisterIdentity, register)
</script>

<template>
  <slot v-if="isRender" />
</template>

<style lang="scss" scoped>
//------------------组件样式------------------
//-------------样式穿透-------------
</style>
